<script setup>

// 更新的数据
import {ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";

import {useUserInfoStore} from '@/store/user.js'
import {userInfoEditService, userInfoGetService} from "@/api/user";
const userInfoStore = useUserInfoStore();//获取个人信息（金额）
//获取个人信息
const getUserInfo = async () => {
    let result = await userInfoGetService();
    //存储pinia
    userInfoStore.info = result.data;
}
getUserInfo()
//个人信息表单数据模型
const infoData = ref({
    account: '',//账号
    password: '',//新密码
    avatar: '',//头像
    mailbox: '',//邮箱
    nickName: '',//昵称
    address:'',//地址
    balance:'',//余额
    oldPassword:'',//要输入的旧密码
})
let token = localStorage.getItem('token');

//上传头像成功回调
const handleAvatarSuccess = (img) => {
    //img就是后台响应的数据，格式为：{code:状态码，message：提示信息，data: 图片的存储地址}
    infoData.value.avatar = img.data
}
//上传头像验证
const beforeAvatarUpload = (rawFile) => {
    const allowedTypes = ['image/jpeg', 'image/png'];
    if (!allowedTypes.includes(rawFile.type)) {
        ElMessage.error('头像必须是 JPG 或 PNG 格式！');
        return false;
    }
    else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('头像大小不能超过5MB！');
        return false;
    }
    return true;
};

const open = () => {
    if(infoData.value.avatar===''&&infoData.value.password===''&&infoData.value.nickName===''&&infoData.value.mailbox===''){
        ElMessage.error("请输入要修改的信息")
        return ;
    }
    // 进行输入验证
    if (!validateInput()) {
        // 如果验证不通过，可以在这里给出错误提示或者其他处理
        ElMessage({
            type: 'error',
            message: errorMessage,
        });
        return; // 阻止提交
    }
    ElMessageBox.prompt('请输入您的密码', '提示', {
        confirmButtonText: '确认提交',
        cancelButtonText: '取消',
        inputPattern:
            /^.{5,16}$/,
        inputErrorMessage: '密码长度必须为5-16位',
        inputType: 'password', // 将类型设置为字符串 "password"
    })
        .then(async ({value}) => {
            infoData.value.oldPassword = value;//绑定传给后端
            const result = await userInfoEditService(infoData.value);
            ElMessage({
                type: 'success',
                message: `修改成功`,
            })
            // 修改成功后刷新页面
            location.reload();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '您已取消修改',
            })
            // 修改失败后刷新页面
            location.reload();
        })
}
//验证失败时的提示错误信息
const errorMessage=ref("")
//验证修改个人信息的内容
const validateInput=()=> {
    const emailRegex = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/; // 邮箱验证
    let isEmailValid = true; // 默认邮箱验证通过

    // 如果输入了邮箱，则进行验证
    if (infoData.value.mailbox) {
        isEmailValid = emailRegex.test(infoData.value.mailbox);
       errorMessage.value="请输入正确的邮箱";
    }
    // 验证昵称
    let isNicknameValid = true; // 默认昵称验证通过

    // 如果输入了昵称，则进行验证
    if (infoData.value.nickName) {
        isNicknameValid = infoData.value.nickName.length > 0 && infoData.value.nickName.length <= 30;
        errorMessage.value="昵称长度为1-30";
    }

    // 验证地址
    let isAddressValid = true; // 默认昵称验证通过

    // 如果输入了地址，则进行验证
    if (infoData.value.address) {
        isAddressValid = infoData.value.address.length > 0 && infoData.value.address.length < 100;
        errorMessage.value="地址长度为1-100";
    }

    // 验证密码
    let isPasswordValid = true; // 默认密码验证通过

    // 如果输入了地址，则进行验证
    if (infoData.value.password) {
        isPasswordValid = infoData.value.password.length >= 5 && infoData.value.password.length <= 16;
        errorMessage.value="密码长度为5-16";
    }
    return isNicknameValid && isEmailValid && isAddressValid&&isPasswordValid;
}
</script>
<template>
    <div class="box">
        <div class="title">个人信息</div>
        <div class="avatar">
            <el-upload
                class="avatar-uploader"
                action="/api/user/uploadAvatar"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :auto-upload="true"
                name="file"
                :headers="{'Authorization':token}"
                :before-upload="beforeAvatarUpload"
            >
                <el-avatar :style="avatarStyle"
                           @mousemove="isHovered=true"
                           @mouseout="isHovered=false"
                           title="单击上传新头像"
                           :src="infoData.avatar || userInfoStore.info.pavatar || require('@/assets/defaultAvatar.jpg')"
                           class="avatar" style="width: 300px; height: 300px;margin-top: 5px;display: inline-block" />
            </el-upload>
        </div>
        <div class="info">
            <el-form  label-width="auto" style="max-width: 500px" :model="infoData">
                <el-form-item label="账号" >
                    <el-input v-model="infoData.account" :placeholder="userInfoStore.info.paccount" disabled />
                </el-form-item>
                <el-form-item label="昵称" >
                    <el-input v-model="infoData.nickName" :placeholder="userInfoStore.info.pnickname"  />
                </el-form-item>
                <el-form-item label="密码">
                    <el-input type="password" v-model="infoData.password" placeholder="密码" show-password />
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="infoData.mailbox" :placeholder="userInfoStore.info.pmailbox"   />
                </el-form-item>
                <el-form-item label="地址" >
                    <el-input v-model="infoData.address" :placeholder="userInfoStore.info.paddress" />
                </el-form-item>
                <el-form-item label="余额" >
                    <el-input v-model="infoData.balance" :placeholder="userInfoStore.info.pbalance"   disabled/>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary"  plain @click="open" style="margin-left: 150px;width: 120px">确认</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
export default {
    name: "PurchaserBasicInfo",
    data() {
        return {
            isHovered: false
        };
    },
    computed: {
        avatarStyle() {
            return {
                transform: this.isHovered ? 'scale(1.2)' : 'scale(1)',
                transition: 'all 0.3s ease'
            };
        }
    }
};
</script>

<style scoped>
/*个人信息的大框架，外部盒子*/
.box {
    width: 80%;
    height: 400px;
    background-color: white;
    margin: 0 auto;
    border-radius: 15px;
    border-left: hotpink solid 5px;
    border-top: #f13b82 solid 2px;
}

/*标题*/
.title {
    margin: 0 auto;
    text-align: center;
    color: rgba(0, 0, 0, 0.66);
    width: 80%;
    border-bottom: #cccccc solid 1px;
    padding-bottom: 5px;
    padding-top: 5px;
}

/*头像*/
.avatar {
    margin-left: 10px;
    display: inline-block;
    float: left;
    margin-top: 20px;
}

/*个人信息*/
.info {
    width: 280px;
    display: inline-block;
    margin-left: 41px;
    border-right: #cccccc solid 1px;
    padding-top: 10px;
}
/*输入框获得焦点时的颜色*/
.el-input{
    --el-input-focus-border-color: pink;
    height: 25px;
    width: 200px;
}
/*//登陆注册按钮的颜色*/
.el-button{
    background-color: hotpink;
    border-color: pink;
    color:white
}
.el-button:hover{
    background-color: pink;
    border-color: pink;
    color:white
}
/*每个信息的间隔*/
.el-form-item{
    margin-bottom: 5px;
}


</style>
